from celery import Celery
import os
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Redis connection with or without authentication
# For Redis without password:
# REDIS_URL = 'redis://localhost:6379/0'

# For Redis with password:
REDIS_URL = 'redis://:Hewenyu1994@121.5.249.100:6379/0'

# For Redis with username and password (Redis 6.0+):
# REDIS_URL = 'redis://username:password@localhost:6379/0'

# Create Celery app with Redis broker and backend
app = Celery('tasks', 
             broker=REDIS_URL,
             backend=REDIS_URL)

# Configure serialization - use JSON for interoperability with Go
app.conf.update(
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    enable_utc=True,
)

# 添加自定义消息处理器，处理Go发送的简单格式消息
# class CustomConsumer(app.consumer_cls):
#     def receive_message(self, *args, **kwargs):
#         try:
#             # 先尝试标准处理
#             message = super().receive_message(*args, **kwargs)
#             if message:
#                 return message
            
#             # 如果标准处理没有返回消息，尝试自定义处理
#             # 注意：此处的逻辑依赖于特定的Celery版本和使用的消息队列
#             # 实际应用中可能需要更复杂的处理
#             return None
#         except Exception as e:
#             logger.error(f"Error receiving message: {e}")
#             return None

# # 使用自定义消息消费者
# app.consumer_cls = CustomConsumer

@app.task(name='tasks.add')
def add(x, y):
    """Simple task that adds two numbers."""
    logger.info(f"Received add task with args: {x}, {y}")
    result = x + y
    print(f"Python add task executed: {x} + {y} = {result}")
    return result

@app.task(name='tasks.concat')
def concat(a, b):
    """Simple task that concatenates two strings."""
    logger.info(f"Received concat task with args: {a}, {b}")
    result = str(a) + str(b)
    print(f"Python concat task executed: '{a}' + '{b}' = '{result}'")
    return result

# 添加一个通用任务处理器，可以处理各种格式的消息
@app.task(name='tasks.process_any', bind=True)
def process_any(self, *args, **kwargs):
    """Process any task with given arguments."""
    logger.info(f"Received generic task with args: {args}, kwargs: {kwargs}")
    task_name = self.request.properties.get('task_name', 'unknown')
    print(f"Processing generic task '{task_name}' with args: {args}, kwargs: {kwargs}")
    
    # 尝试找到并执行对应的任务
    if task_name == 'add' and len(args) >= 2:
        return add(args[0], args[1])
    elif task_name == 'concat' and len(args) >= 2:
        return concat(args[0], args[1])
    else:
        return {"status": "completed", "args": args, "kwargs": kwargs}

if __name__ == '__main__':
    # Run Celery worker if script is executed directly
    os.system('celery -A tasks worker --loglevel=info --pool=solo') 